package com.xcl.interceptor;

import com.xcl.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行所有预检请求
        if("OPTIONS".equalsIgnoreCase(request.getMethod())){
            return true;
        }
        //验证token
        String token = request.getHeader("Authorization");
        try {
            System.out.println("拦截器拦截请求，获取的token是："+token);
            Map<String,Object> claims = JwtUtil.parseToken(token);
            return true;
        }catch (Exception e){
            response.setStatus(401);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的token");
            return false;
        }
    }
}
